package com.ruolin.micro.gateway.server.utils;


import org.apache.commons.lang3.StringUtils;

import java.util.Set;
import java.util.stream.Collectors;

/**
 * dubbo service utils class
 */
public class DubboServiceUtils {
    private static final String PRES = "providers:";
    private static final String PRE = "provider:";
    private static final String SUFFIX = ":";

    private DubboServiceUtils() {
        throw new AssertionError("No com.github.dubbo.example.utils.DubboServiceUtils instances for you!");
    }

    public static String buildServiceName(String interfaceName, String version) {
        StringBuilder serviceNameBuilder = new StringBuilder(PRES);
        return serviceNameBuilder.append(interfaceName)
                .append(":")
                .append(version)
                .toString();
    }

    public static Set<String> filterDubboService(Set<String> serviceNames) {
        return serviceNames
                .stream()
                .filter(s -> s.startsWith(PRES))
                .collect(Collectors.toSet());
    }

    public static String getMethod(String requestURL) {
        int beginIndex = StringUtils.lastIndexOf(requestURL, "/") + 1;
        return requestURL.substring(beginIndex);
    }

    public static String getDataId(String interfaceName, String version, String group, String application) {
        final StringBuilder dataIdBuilder = new StringBuilder(interfaceName);
        dataIdBuilder.append(":").append(version);
        if (group == null) {
            return dataIdBuilder
                    .append("::")
                    .append(PRE)
                    .append(application)
                    .toString();
        }

        return dataIdBuilder
                .append(":")
                .append(group)
                .append(":")
                .append(PRE)
                .append(application)
                .toString();
    }

}
